package test;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
@WebServlet(name = "productServlet",urlPatterns = "/product")
public class ProductServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    public static String getCookieValueByName(HttpServletRequest request,String name) {
        Cookie[] cs=request.getCookies();

        if(cs==null)
            return null;
        for(Cookie cookie:cs){
            System.out.println(cookie.getName()+":"+cookie.getValue());
            if (cookie.getName().equals(name)) {
                return cookie.getValue();
            }
        }
        return  null;
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String productName = request.getParameter("name");
        String product = getCookieValueByName(request, "product");

        if(product!=null){

            String[] ps=product.split("#");
            Set<String> productSet = new HashSet<>(Arrays.asList(ps));
            productSet.add(productName);

            product="";
            for (String p : productSet) {
                product+=p+"#";
            }

        }else {
            product = productName;
        }

        Cookie cookie=new Cookie("product",product);
        response.addCookie(cookie);

        response.sendRedirect("product.jsp");

    }
}
